package handler

import (
	"gitee.com/sansaniot/ssiot-core/logger"
	"gitee.com/sansaniot/ssiot-core/msg/email"
	"github.com/valyala/fasttemplate"
	"gorm.io/gorm"

	"ssnotify/common/enums/recordstatus"
	"ssnotify/common/enums/sendway"
	"ssnotify/common/utils"
	"ssnotify/internal/notify/models"
)

// 邮件通知
func SendEmailNotify(db *gorm.DB, templateId string, notifyData map[string]interface{}, notifyConfig models.NotifyConfig, notifyUserList []models.NotifyUser) {
	if len(templateId) == 0 {
		return
	}
	//日志
	logger.Info("************发送邮件通知开始************")
	//获取当前通知对应的模板配置集合
	notifyTemplateList := getNotifyTemplateList(db, templateId, sendway.Email.Get().SendType)
	//遍历用户信息(每个用户发送一次获取成功或失败响应)
	for _, userItem := range notifyUserList {
		toEmail := userItem.Email
		if len(toEmail) == 0 {
			continue
		}
		var sendResult models.NotifySendResult
		sendResult.SendStatus = recordstatus.NotSend.Get().Key
		sendResult.SendWay = sendway.Email.Get().SendType
		for _, notifyTemplate := range notifyTemplateList {
			sendEmail(toEmail, notifyData, notifyTemplate, &sendResult)
		}
		//初始化缓存通知记录
		addNotifyRecordQueue(notifyData, notifyConfig, userItem, &sendResult)
	}
}

// 发送邮件
func sendEmail(sendEmail string, notifyData map[string]interface{}, notifyTemplate models.NotifyTemplate, sendResult *models.NotifySendResult) {
	if len(sendEmail) == 0 {
		return
	}
	//邮件通知模板参数
	emailContent := formatNotifyEmailContent(notifyTemplate.Content, notifyData)
	//邮件工具类
	if err := email.SendEmailByData("系统通知", emailContent, []string{sendEmail}); err != nil {
		sendResult.SendStatus = utils.If(sendResult.SendStatus != recordstatus.NotSend.Get().Key, sendResult.SendStatus, recordstatus.SendFail.Get().Key).(string)
		sendResult.ErrorInfo = utils.If(sendResult.SendStatus != recordstatus.SendFail.Get().Key, sendResult.ErrorInfo, err.Error()).(string)
		logger.Errorf("邮件通知发送异常 err=[%+v]", err)
	} else {
		sendResult.SendStatus = recordstatus.SendSuccess.Get().Key
		logger.Infof("邮件通知发送成功 email=[%+v]", sendEmail)
	}
	//判断是否指定通知content
	if len(utils.GetStringValueFiled(notifyData, "remark")) == 0 {
		if len(sendResult.SendContent) == 0 {
			sendResult.SendContent = make([]map[string]string, 0)
		}
		sendResult.SendContent = append(sendResult.SendContent, map[string]string{"email": emailContent})
	}
}

// 获取通知模板
func formatNotifyEmailContent(emailContent string, notifyData map[string]interface{}) string {
	//格式处理
	formatItem := make(map[string]interface{})
	for k, v := range notifyData {
		formatItem[k] = utils.InterfaceToStr(v)
	}
	//创建模板替换工具类
	tpl := fasttemplate.New(emailContent, "${", "}")
	//使用明细内容替换模板占位符
	return tpl.ExecuteString(formatItem)
}
